#include "duktapemanager.h"

DuktapeManager::DuktapeManager()
    : m_ctx(NULL)
{

}

DuktapeManager::~DuktapeManager()
{
    cleanDukTape();
}

bool DuktapeManager::initDukTape(void)
{
    if(m_ctx != NULL)
        return true;

    m_ctx = duk_create_heap_default();
    if (m_ctx == NULL) {
        return false;
    }

    return true;
}

void DuktapeManager::cleanDukTape(void)
{
    if(m_ctx == NULL)
        return;

    duk_destroy_heap(m_ctx);
    m_ctx = NULL;
}

/// 执行脚本
void DuktapeManager::runScript(const char* scriptStr)
{
    if(m_ctx == NULL || scriptStr == "")
        return;

    try {
        if (duk_peval_string(m_ctx, scriptStr) != 0) {
            throw std::runtime_error(duk_safe_to_string(m_ctx, -1));
        }
        duk_pop(m_ctx);
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
}
